package demo523;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    public int addUser(String username, String password) throws SQLException, ClassNotFoundException {
        //1.连接数据库
        Connection connection = SqlConnection.getCon();
        //2.编写sql语句
        String sql = "insert into users(username,password) values(?,?)";
        //3.执行sql语句
        PreparedStatement preparedStatement = connection.prepareStatement(sql);// 预编译sql语句
        //给问号进行赋值
        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);
        return preparedStatement.executeUpdate();
    }


    public Users login(String username, String password) throws SQLException, ClassNotFoundException {
        Users users = null;
        int i = 1;

        Connection connection = SqlConnection.getCon();

        String sql = "select * from users where username=? and password=?";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        preparedStatement.setString(1, username);
        preparedStatement.setString(2, password);

        ResultSet resultSet = preparedStatement.executeQuery();

        if (resultSet.next()){
            users = new Users();
            users.setId(resultSet.getInt("id"));
            users.setUsername(resultSet.getString("username"));
            users.setPassword(resultSet.getString("password"));
        }
        return users;
    }
    public int deleteUser(int id) throws SQLException, ClassNotFoundException {
        Connection connection = SqlConnection.getCon();
        String sql = "delete from users where id=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,id);
        return preparedStatement.executeUpdate();
    }
}

